# frozen_string_literal: true

module Wpxf
  module Net
    # A response from a request made by a HttpClient.
    class HttpResponse
      # @param res [Object] a response to parse.
      def initialize(res)
        parse_typhoeus_response(res) if res.is_a? Typhoeus::Response
      end

      # Parse a Typhoeus response into the object.
      # @param res [Typhoeus::Response] the response object to parse.
      # @return [nil]
      def parse_typhoeus_response(res)
        self.code = res.code
        self.body = res.body.nil? ? '' : res.body
        self.headers = res.headers
        self.timed_out = res.timed_out? || res.return_code == :couldnt_connect
        self.cookies = CookieJar.new.parse(res.headers['Set-Cookie']) if res.headers
      end

      # @return [Boolean] a boolean that indicates whether a request timed out.
      def timed_out?
        timed_out
      end

      # @return [Integer] the HTTP status code.
      attr_accessor :code

      # @return [String] the response body.
      attr_accessor :body

      # @return [Hash] a hash of all returned headers.
      attr_accessor :headers

      # @return [Boolean] a boolean that indicates whether a request timed out.
      attr_accessor :timed_out

      # @return [Hash] a {CookieJar} with all returned cookies.
      attr_accessor :cookies
    end
  end
end
